import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { map } from "rxjs";

@Injectable()
export class ResponseInterceptor implements NestInterceptor {

  intercept(context: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(
      map((data) => {
        /** 
         * undefined默认为成功
         */
        if (data===undefined) return processResponse({
          code: 1,
          data: {}
        })

        const dataType = Object.prototype.toString.call(data);
        /**
         * 数组包一层
         */
        if (dataType === '[object Array]') {
          return processResponse({
            code: 1,
            data,
          })
        }
        /**
         * 对象包一层
         */
        if (dataType === '[object Object]') {
          const keys = Object.keys(data);
          if (
            (data.code == 1 && keys.includes('data')) ||
            (keys.includes('code') && keys.includes('message'))
          ) { // 已经包过就不包了
            return processResponse(data);
          } else { // 包一层
            return processResponse({
              code: 1,
              data,
            })
          }
        }
        
        /** 
         * 其他情况不做处理
         */
        return data;
      })
    )
  }
}

/**
 * 处理响应，兼容不同框架格式
 */
export function processResponse(data: any) {
  /** 
   * 设置success
   */
  data.success = data.code == 1;
  return data;
}